package com.example.writting.ui.words

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.writting.databinding.FragmentWordsBinding
import com.google.android.material.chip.Chip
import com.example.writting.model.FlowStep
import com.example.writting.model.QAStructure
import com.example.writting.model.MajorTitle
import com.example.writting.model.MinorTitle
import com.example.writting.model.Content
import com.example.writting.model.ContentType
import com.example.writting.ui.words.content.allContents
import com.example.writting.ui.words.content.TaggedContent

class WordsFragment : Fragment() {

    private var _binding: FragmentWordsBinding? = null
    private val binding get() = _binding!!
    private lateinit var contentAdapter: WordContentAdapter
    private var selectedPrimaryTag: String? = null
    private var selectedSecondaryTag: String? = null

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentWordsBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        setupRecyclerView()
        setupPrimaryTagGroup()
        setupSecondaryTagGroup()
        setupContentChipGroup()

        // 默认选中第一个一级标签
        (binding.primaryTagGroup.getChildAt(0) as? Chip)?.isChecked = true
    }

    private fun updateContent(tag: String) {
        contentAdapter.updateContents(allContents[tag]?.contents ?: emptyList())
    }

    private fun setupRecyclerView() {
        contentAdapter = WordContentAdapter()
        binding.contentList.layoutManager = LinearLayoutManager(requireContext())
        binding.contentList.adapter = contentAdapter
    }

    private fun setupPrimaryTagGroup() {
        val primaryTags = allContents.values.map { it.primaryTag }.distinct()
        primaryTags.forEach { tag ->
            val chip = Chip(requireContext()).apply {
                text = tag
                isCheckable = true
                setOnCheckedChangeListener { _, isChecked ->
                    if (isChecked) {
                        selectedPrimaryTag = tag
                        updateSecondaryTagGroup(tag)
                        updateContentChipGroup()
                    }
                }
            }
            binding.primaryTagGroup.addView(chip)
        }
    }

    private fun setupSecondaryTagGroup() {
        // Secondary tag group will be updated when primary tag is selected
    }

    private fun updateSecondaryTagGroup(primaryTag: String) {
        binding.secondaryTagGroup.removeAllViews()
        val secondaryTags = allContents.values
            .filter { it.primaryTag == primaryTag }
            .map { it.secondaryTag }
            .distinct()

        secondaryTags.forEach { tag ->
            val chip = Chip(requireContext()).apply {
                text = tag
                isCheckable = true
                setOnCheckedChangeListener { _, isChecked ->
                    if (isChecked) {
                        selectedSecondaryTag = tag
                        updateContentChipGroup()
                    }
                }
            }
            binding.secondaryTagGroup.addView(chip)
        }

        // 默认选中第一个二级标签
        if (secondaryTags.isNotEmpty()) {
            (binding.secondaryTagGroup.getChildAt(0) as? Chip)?.isChecked = true
        }
    }

    private fun setupContentChipGroup() {
        // Content chip group will be updated when both primary and secondary tags are selected
    }

    private fun updateContentChipGroup() {
        binding.tagGroup.removeAllViews()
        
        if (selectedPrimaryTag == null || selectedSecondaryTag == null) return

        val filteredTopics = allContents.filter { (_, content) ->
            content.primaryTag == selectedPrimaryTag && content.secondaryTag == selectedSecondaryTag
        }.keys

        filteredTopics.forEach { topic ->
            val chip = Chip(requireContext()).apply {
                text = topic
                isCheckable = true
                setOnCheckedChangeListener { _, isChecked ->
                    if (isChecked) {
                        updateContent(topic)
                    }
                }
            }
            binding.tagGroup.addView(chip)
        }

        // 默认选中第一个内容标签
        if (filteredTopics.isNotEmpty()) {
            (binding.tagGroup.getChildAt(0) as? Chip)?.isChecked = true
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}